package com.june.junemplayer.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelStoreOwner;

import com.june.junemplayer.R;
import com.june.junemplayer.base.BaseActivity;
import com.june.junemplayer.controller.GlobalViewModelController;
import com.june.junemplayer.receiver.InitReceiver;
import com.june.junemplayer.service.OverlayWindowService;
import com.june.junemplayer.service.OverlayWindowView;

import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends BaseActivity {

    private TranslateAnimation mTranslateAnimation;
    private GlobalViewModelController mGlobalViewModelController;

    private OverlayWindowService mBindService;

    private TextView mTranslate;

    private static final String[] permissions=new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.SYSTEM_ALERT_WINDOW
    };

    @Override
    protected void initBeforeView(Bundle savedInstanceState) {
        Log.d("JuneProcedure", getTag() + "----initBeforeView");

        mGlobalViewModelController = new GlobalViewModelController((ViewModelStoreOwner) getApplication());
    }

    @Override
    protected void bindView(Bundle savedInstanceState) {
        Log.d("JuneProcedure", getTag() + "----bindView");
        mTranslate = findViewById(R.id.tv_translate);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        Log.d("JuneProcedure", getTag() + "----initData");
        int permissionCheck=0;
        for(String permission:permissions){
            permissionCheck+=this.checkSelfPermission(permission);
        }
        if (!Settings.canDrawOverlays(this)) {
            startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
        }else if(permissionCheck != PackageManager.PERMISSION_GRANTED){
            this.requestPermissions(permissions,1);
        }else{
            AfterPermissionInitData();
        }
    }


    private void AfterPermissionInitData() {
        Log.d("JuneProcedure", getTag() + "----initData");

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mGlobalViewModelController.init(mActivity);
            }
        });
        mTranslate.post(new Runnable() {
            @Override
            public void run() {
                //通过post拿到的tvTranslate.getWidth()不会为0。
                mTranslateAnimation = new TranslateAnimation(0, mTranslate.getWidth(), 0, 0);
                mTranslateAnimation.setDuration(1000);
                mTranslateAnimation.setFillAfter(true);
                mTranslate.startAnimation(mTranslateAnimation);
                //动画监听
                mTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        Intent intent =new Intent(mActivity, OverlayWindowService.class);
                        bindService(intent, connectionOverlayWindowServiceConnection, Context.BIND_AUTO_CREATE);
                        InitReceiver initReceiver = new InitReceiver();
                        IntentFilter itFilter = new IntentFilter();
                        itFilter.addAction(InitReceiver.VIEW_INIT);
                        registerReceiver(initReceiver, itFilter);
                        sendBroadcast(new Intent(InitReceiver.VIEW_INIT));
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
            }
        });
    }

    /**
     * Service连接
     */
    private ServiceConnection connectionOverlayWindowServiceConnection =new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBindService = ((OverlayWindowService.OverlayWindowServiceBinder) iBinder).getService();
            Log.d("JuneProcedure",getTag()+"----onServiceConnect----OverlayWindowService");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("JuneProcedure",getTag()+"----onServiceDisconnected----OverlayWindowService");
        }
    };


    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected String getTag() {
        return "SplashActivity";
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            for (int i=0;i<grantResults.length;i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Log.d("June","Need Permission"+i);
                    this.requestPermissions( new String[]{permissions[i]},1);
                }
            }
            for(int i=0;i<grantResults.length;i++){
                int count=0;
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    count++;
                }
                if (count==grantResults.length){
                    AfterPermissionInitData();
                }
            }
        }
    }

}